package net.yebaihe.wc;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import net.yebaihe.wc.QQ.utils.TokenStore;
import net.yebaihe.wc.sina.OAuthConstant;
import weibo4android.Weibo;
import weibo4android.WeiboException;
import weibo4android.http.RequestToken;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ToggleButton;

import com.kaixin.connect.Kaixin;
import com.kaixin.connect.Util;
import com.kaixin.connect.exception.KaixinAuthError;
import com.kaixin.connect.exception.KaixinError;
import com.kaixin.connect.listener.KaixinAuthListener;
import com.renren.api.connect.android.Renren;
import com.renren.api.connect.android.exception.RenrenAuthError;
import com.renren.api.connect.android.exception.RenrenException;
import com.renren.api.connect.android.feed.FeedPublishRequestParam;
import com.renren.api.connect.android.view.RenrenAuthListener;
import com.tencent.weibo.api.T_API;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.Configuration;
import com.tencent.weibo.utils.OAuthClient;

public class SNS extends StateMachine{

	private EditText edtTxtSNS;
	private ToggleButton togSina;
	private ToggleButton togQQ;
	private ToggleButton togRR;
	public static OAuth oauth;
	public static OAuthClient auth;
	Renren renren;
	KaixinAuthListener authListener = new KaixinAuthListener() {
		@Override
		public void onAuthCancel(Bundle values) {
			togKX.setChecked(false);
		}

		@Override
		public void onAuthCancelLogin() {
			togKX.setChecked(false);
		}

		@Override
		public void onAuthComplete(Bundle values) {
			Toast.makeText(SNS.this, "开心网认证成功！", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onAuthError(KaixinAuthError kaixinAuthError) {
			togKX.setChecked(false);
		}
	};
	final RenrenAuthListener listener = new RenrenAuthListener() {

		@Override
		public void onComplete(Bundle values) {
			new Handler().post(new Runnable(){
				@Override
				public void run() {
					Toast.makeText(SNS.this, "人人网认证成功！", Toast.LENGTH_SHORT).show();
				}
			});
		}

		@Override
		public void onRenrenAuthError(
				RenrenAuthError renrenAuthError) {
			togRR.setChecked(false);
		}

		@Override
		public void onCancelLogin() {
			togRR.setChecked(false);
		}

		@Override
		public void onCancelAuth(Bundle values) {
			togRR.setChecked(false);
		}
		
	};
	private ToggleButton togKX;
	protected ProgressDialog qqProgressDialog=null;
	protected ProgressDialog sinaProgressDialog=null;

	
	@Override
	protected String getTopbarTitle() {
		String title="未知地点";
		SQLiteDatabase db = MyHelper.get(this).getReadableDatabase();
		if (db!=null){
			Cursor c=db.rawQuery("select * from sessions where _id="+getIntent().getIntExtra("sessionid", -1), null);
			if (c.moveToFirst()){
				int rid=c.getInt(4);
				c.close();
				c=db.rawQuery("select * from restaurants where _id="+rid, null);
				if (c.moveToFirst()){
					title=c.getString(1);
				}
			}
			c.close();
			db.close();
		}
		return title;
	}

	@Override
	protected void prepareClient(View client) {
		renren = new Renren("5ccd39fdeff943218235c4945cf789bf", "79d7418f7c0642f3bb1ad53e00342e33","171837",SNS.this); 
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);  
        System.setProperty("weibo4j.oauth.consumerSecret",Weibo.CONSUMER_SECRET); 
		togSina=(ToggleButton) client.findViewById(R.id.chboxsina);
		edtTxtSNS=(EditText)client.findViewById(R.id.edtSnsCnt);
		
		SQLiteDatabase db = MyHelper.get(this).getReadableDatabase();
		Cursor r=db.rawQuery("select * from restaurants where _id in(select restaurant from sessions where _id="+getWCAppContext().sessionid+") ", null);
		r.moveToFirst();
		edtTxtSNS.setText("我在"+r.getString(1)+"完成点餐，大家也来试试吧。地址：http://t.cn/SqPywg.");
		r.close();
		db.close();
		
		togSina.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if (arg1){
					if (!sinaAccessOK()){
						sinaProgressDialog=ProgressDialog.show(SNS.this, "", "正在打开新浪微博的授权页面...");
						new Handler().postDelayed(new Runnable(){
							@Override
							public void run() {
								Weibo weibo = new Weibo();  
								RequestToken requestToken;  
								try  
								{  
									requestToken = weibo.getOAuthRequestToken("weican://net.yebaihe.sina");  
									OAuthConstant.getInstance().setRequestToken(requestToken);  
									Uri uri = Uri.parse(requestToken.getAuthenticationURL());  
									startActivity(new Intent(Intent.ACTION_VIEW, uri));  
								}  
								catch (WeiboException e)  
								{
									e.printStackTrace();
								}  
							}
						}, 500);
					}
				}
			}
		});
		togQQ=(ToggleButton) client.findViewById(R.id.chboxqq);
		togRR=(ToggleButton) client.findViewById(R.id.togrr);
		togKX=(ToggleButton) client.findViewById(R.id.togKX);
		togKX.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if (arg1){
					Kaixin kaixin = Kaixin.getInstance();
					kaixin.loadStorage(SNS.this);
					if (!kaixin.isSessionValid()) {
						String[] permissions = {"basic", "create_records"};
						kaixin.authorize(SNS.this, permissions, authListener);
					}
				}
			}
		});
		togRR.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if (arg1){
					renren.authorize(SNS.this, null, listener, 1);					
				}
			}
		});
		togQQ.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if (arg1){
					oauth = new OAuth("weican://net.yebaihe.qq");
					String[] oauth_token_array = TokenStore.fetch(SNS.this);
					String oauth_token = oauth_token_array[0];
					String oauth_token_secret = oauth_token_array[1];
					if(oauth_token == null || oauth_token_secret == null) {
						qqProgressDialog=ProgressDialog.show(SNS.this, "", "正在打开腾讯微博的授权页面...");
						new Handler().postDelayed(new Runnable(){
							@Override
							public void run() {
								auth = new OAuthClient();// OAuth 认证对象
								try {
									oauth = auth.requestToken(oauth);
									if (oauth.getStatus() == 1) {
										Toast.makeText(SNS.this, "请求认证失败!", Toast.LENGTH_SHORT).show();
										qqProgressDialog.dismiss();
										qqProgressDialog=null;
										return;
									} else {
										String oauth_token1 = oauth.getOauth_token();
										String url = "http://open.t.qq.com/cgi-bin/authorize?oauth_token="
												+ oauth_token1;
										Uri uri = Uri.parse(url);
										startActivity(new Intent(Intent.ACTION_VIEW, uri));
									}
								} catch (Exception e) {
									e.printStackTrace();
								}	
							}
						}, 500);
					}
				}
			}
		});
		
		Button btnCancel=(Button)client.findViewById(R.id.btncancel);
		btnCancel.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		Button btnSend=(Button)client.findViewById(R.id.btnSend);
		btnSend.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				if (sinaAccessOK() && togSina.isChecked()){
			        SharedPreferences settings = getSharedPreferences(Index.PREFS_NAME, 0);  
			        String sinakey=settings.getString("sinakey", "");
			        String sinasecret=settings.getString("sinasecret", "");
	                Weibo weibo = OAuthConstant.getInstance().getWeibo();  
	                weibo.setToken(sinakey,sinasecret);
	                try {
						weibo.updateStatus(getSnsCnt());
						Toast.makeText(SNS.this, "同步到新浪微博成功！", Toast.LENGTH_SHORT).show();
					} catch (WeiboException e) {
						e.printStackTrace();
					}
				}
				//TX
				oauth = new OAuth("weican://net.yebaihe.qq");
				String[] oauth_token_array = TokenStore.fetch(SNS.this);
				String oauth_token = oauth_token_array[0];
				String oauth_token_secret = oauth_token_array[1];
				if(oauth_token != null && oauth_token_secret != null && togQQ.isChecked()) {
					oauth.setOauth_token(oauth_token);
					oauth.setOauth_token_secret(oauth_token_secret);
					T_API tapi = new T_API();
					String content = getSnsCnt();
					try {
						tapi.add(oauth, "json", content, Configuration.wifiIp, "", "");
						Toast.makeText(SNS.this, "同步到腾讯微博成功！", Toast.LENGTH_SHORT).show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
				if (togRR.isChecked()){
					FeedPublishRequestParam feed=new FeedPublishRequestParam("聚餐", getSnsCnt(), "http://weibo.com/woshilily", "", "", "", "", "");
					try {
						renren.publishFeed(feed);
						Toast.makeText(SNS.this, "同步到人人网成功！", Toast.LENGTH_SHORT).show();
					} catch (RenrenException e) {
						e.printStackTrace();
					} catch (Throwable e) {
						e.printStackTrace();
					}
				}
				
				if (togKX.isChecked()){
					Kaixin kaixin = Kaixin.getInstance();
					kaixin.loadStorage(SNS.this);
					if (kaixin.isSessionValid()) {
						Bundle bundle = new Bundle();
						bundle.putString("content", getSnsCnt());
						try {
							String jsonResult = kaixin.uploadContent(SNS.this, "/records/add.json", bundle, null);
							if (jsonResult != null) {
								KaixinError kaixinError = Util.parseRequestError(jsonResult);
								if (kaixinError == null) {
									long rid = getRecordID(jsonResult);
									if (rid > 0) {
										Toast.makeText(SNS.this, "同步到开心网成功！", Toast.LENGTH_SHORT).show();
									}
								}
							}
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (MalformedURLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		});
		
		togSina.setText("");
		togSina.setTextOff("");
		togSina.setTextOn("");
		togQQ.setText("");
		togQQ.setTextOff("");
		togQQ.setTextOn("");
		togRR.setText("");
		togRR.setTextOff("");
		togRR.setTextOn("");
		togKX.setText("");
		togKX.setTextOff("");
		togKX.setTextOn("");
	}
	private long getRecordID(String jsonResult) throws JSONException {
		JSONObject jsonObj = new JSONObject(jsonResult);
		if (jsonObj == null) {
			return 0l;
		}

		long rid = jsonObj.optInt("rid");
		return rid;
	}

	protected String getSnsCnt() {
		return edtTxtSNS.getText().toString();
	}

	protected boolean sinaAccessOK() {
        SharedPreferences settings = getSharedPreferences(Index.PREFS_NAME, 0);  
        String sinakey=settings.getString("sinakey", "");
        return sinakey.length()>0;
	}

	@Override
	protected int getLayoutRes() {
		return R.layout.sns;
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (renren != null) {
			renren.authorizeCallback(requestCode, resultCode, data);
		}
	}

	@Override
	public void onResume(){
		super.onResume();
		
		if (qqProgressDialog!=null){
			qqProgressDialog.dismiss();
			qqProgressDialog=null;
		}

		if (sinaProgressDialog!=null){
			sinaProgressDialog.dismiss();
			sinaProgressDialog=null;
		}
		
		if (!sinaAccessOK()){
			togSina.setChecked(false);
		}
		
		oauth = new OAuth("weican://net.yebaihe.qq");
		String[] oauth_token_array = TokenStore.fetch(SNS.this);
		String oauth_token = oauth_token_array[0];
		String oauth_token_secret = oauth_token_array[1];
		if ((oauth_token==null) || (oauth_token_secret==null)){
			togQQ.setChecked(false);
		}
		
		if (!renren.isAccessTokenValid()){
			togRR.setChecked(false);
		}
		
		if (!Kaixin.getInstance().isSessionValid()){
			togKX.setChecked(false);
		}
		togQQ.setEnabled(true);
		togSina.setEnabled(true);
		
		
	}
	
}
